package com.lzy.web.redis;

import com.alibaba.fastjson.JSON;
import com.lzy.business.facade.AgentProfitFacade;
import com.lzy.business.facade.MemberBuyFacade;
import com.lzy.business.facade.OrderProductFacade;
import com.lzy.business.param.MemberBuyCouponParam;
import com.lzy.common.apis.ParamServiceApi;
import com.lzy.common.constants.CommonConstants;
import com.lzy.common.dtos.ParamBaseDto;
import com.lzy.framework.core.datasource.multiple.DataSource;
import com.lzy.framework.core.datasource.multiple.DataSourceHolder;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.framework.core.utils.StringUtil;
import com.lzy.framework.tools.kv.KvClient;
import com.lzy.order.apis.OrderApi;
import com.lzy.order.dtos.OrderInfoDTO;
import com.lzy.order.dtos.coupon.MotorCouponInfoDTO;
import com.lzy.payment.dtos.queue.AgentSaleDTO;
import com.lzy.payment.dtos.queue.MsgSetMealDTO;
import com.lzy.product.apis.*;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.OrderProductDto;
import com.lzy.product.dtos.OrderProjectRecordDto;
import com.lzy.product.dtos.ProductInfoProjectDto;
import com.lzy.product.dtos.agent.AgentOrderInfoDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class InitQueue implements ApplicationListener<ContextRefreshedEvent> {
    private static final Logger LOGGER = LoggerFactory.getLogger(InitQueue.class);
    /**
     * 分布式锁超时时间
     */
    private static final int SETNX_EXPIRED_SECOND = 10 * 60;

    @Autowired
    private KvClient kvClient;

    @Autowired
    private OrderProductServiceApi orderProductServiceApi;

    @Autowired
    private ProductClassifyServiceApi productClassifyServiceApi;

    @Autowired
    private OrderProjectRecordServiceApi orderProjectRecordServiceApi;

    @Autowired
    private ProductInfoProjectServiceApi productInfoProjectServiceApi;

    @Autowired
    private ParamServiceApi paramServiceApi;

    @Autowired
    private MemberBuyFacade memberBuyFacade;

    @Autowired
    private OrderProductFacade orderProductFacade;

    @Autowired
    AgentOrderInfoServiceApi agentOrderInfoServiceApi;

    @Autowired
    AgentProfitFacade agentProfitFacade;

    @Autowired
    private OrderApi orderApi;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() != null) {

            // TODO 待优化，提取线程池工具
            ExecutorService fixedThreadPool = Executors.newFixedThreadPool(8);

            // 产品套餐订单超时未确认，自动拒绝
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    orderProductConfirm();
                }
            });
            // 代理商订单超时未确认，自动拒绝
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    orderAgentConfirm();
                }
            });
            // 产品套餐支付成功后业务流程
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    orderProductSuccess();
                }
            });
            // 代理商协议支付成功后业务流程
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    orderAgentProtocolSuccess();
                }
            });
            // 代理商产品支付成功后业务流程
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    orderAgentProductSuccess();
                }
            });
            // 卡券宝会员购买卡券支付成功后业务流程
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    memberBuyCouponSuccess();
                }
            });
            // 处理支付时间：zset
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        handleOrderPayTimeZset();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            fixedThreadPool.shutdown();
        }
    }

    ///////////////////////////////////////////////////// 处理订单支付时间/////////////////////////////////////////////////////////

    /**
     * 处理订单支付时间:集合------订单支付时间,如果小于当前的时间戳，那么就放入消息队列上
     * <p>
     * zset的key：zset:queue:order:payTime 消息队列名称：queue:order:payTime
     *
     * @throws InterruptedException
     */
    private void handleOrderPayTimeZset() throws InterruptedException {
        Jedis jedis = kvClient.getJedis();
        Set<String> msgSet = null;
        long timeStamp = 0;
        Iterator<String> iterator = null;
        StringBuilder sb = new StringBuilder();
        String key = BusinessType.QueueKey.ZSET_LOCK;
        Long result = null;
        Long l = null;
        Long count = null;
        while (true) {
            try {
                // TODO 如果当前线程挂了，咋整；二期做调整
                result = jedis.setnx(key, "300000");
                // 设置超时时间
                jedis.expire(key, SETNX_EXPIRED_SECOND);
                if (result == 1) {
                    timeStamp = System.currentTimeMillis();
                    msgSet = jedis.zrangeByScore(BusinessType.QueueKey.ZSET + BusinessType.QueueKey.QUEUE_ORDER_PAY_TIME, 0, timeStamp);
                    if (msgSet == null || msgSet.isEmpty()) {
                        jedis.del(key);
                        Thread.sleep(2000);
                        continue;
                    }
                    iterator = msgSet.iterator();
                    while (iterator.hasNext()) {
                        String msg = iterator.next();
                        if (!StringUtil.isBlank(msg)) {
                            sb.append(msg).append(",");
                            // 放入消息队列
                            l = jedis.rpush(BusinessType.QueueKey.QUEUE_ORDER_PAY_TIME, msg);
                            if (l == null) {
                                // TODO 失败咋整？重新加？
                                LOGGER.error("订单支付时间：放入队列======失败======订单号:" + msg);
                            }
                        }
                    }
                    count = jedis.zremrangeByScore(BusinessType.QueueKey.ZSET + BusinessType.QueueKey.QUEUE_ORDER_PAY_TIME, 0, timeStamp);
                    if (count == null) {
                        LOGGER.error("订单支付时间：删除zset======失败======订单号:" + sb.toString());
                    }
                    sb.setLength(0);
                    iterator = null;
                    msgSet = null;

                } else {
                    Thread.sleep(2000);
                }

            } finally {
                if (result == 1) {
                    jedis.del(key);
                }

            }
        }
    }

    /**
     * @Description:产品订单自动完结
     * @Date:2017/12/12 16:02
     */
    private void orderProductConfirm() {
        Jedis jedis = kvClient.getJedis();
        Set<String> msgSet = null;
        while (true) {
            try {
                long timeStamp = System.currentTimeMillis();
                msgSet = jedis.zrangeByScore(BusinessType.QueueKey.ZSET + BusinessType.QueueKey.QUEUE_PRODUCT_ORDER_PAY_TIME, 0, timeStamp);
                if (msgSet == null || msgSet.size() == 0) {
                    Thread.sleep(100);
                    continue;
                } else {
                    for (String orderId : msgSet) {
                        System.out.println("执行产品订单自动失效，for循环进入======订单编号: " + orderId);
                        LOGGER.info("执行产品订单自动失效，for循环进入======订单编号: " + orderId);
                        OrderProductDto orderProductDto = orderProductServiceApi.findById(Long.parseLong(orderId));
                        if (orderProductDto == null) {
                            continue;
                        }
                        if (orderProductDto.getStatus() != null && orderProductDto.getStatus().equals(BusinessType.OrderType.PAYING.getCode())) {
                            OrderProductDto dto = new OrderProductDto();
                            dto.setOrderId(Long.parseLong(orderId));
                            dto.setStatus(BusinessType.OrderType.CLOSED.getCode());//此时表示已关闭的订单
                            dto.setRemark("订单过期自动失效");
                            // 半小时未确认订单，自动按失效处理。
                            if (orderProductServiceApi.update(dto)) {
                                //释放产品分类对应的库存量
                                productClassifyServiceApi.updateSurplusByProductId(orderProductDto.getProductId(), orderProductDto.getCount(), "+");
                                LOGGER.info("执行产品订单自动失效，成功的取消待支付状态======订单编号: " + orderId);
                            } else {
                                LOGGER.info("执行产品订单自动失效，未成功取消待支付状态======订单编号: " + orderId);
                            }
                        }
                    }
                }
                jedis.zremrangeByScore(BusinessType.QueueKey.ZSET + BusinessType.QueueKey.QUEUE_PRODUCT_ORDER_PAY_TIME, 0, timeStamp);
            } catch (Exception e) {
                LOGGER.error("产品订单自动完结确认:执行操作======异常: ");
                e.printStackTrace();
            }
        }
    }

    /**
     * @Description:代理商订单自动完结
     * @Date:2017/12/12 16:02
     */
    private void orderAgentConfirm() {
        Jedis jedis = kvClient.getJedis();
        Set<String> msgSet = null;
        while (true) {
            try {
                long timeStamp = System.currentTimeMillis();
                msgSet = jedis.zrangeByScore(BusinessType.QueueKey.ZSET + BusinessType.QueueKey.QUEUE_PRODUCT_ORDER_PAY_TIME, 0, timeStamp);
                if (msgSet == null || msgSet.size() == 0) {
                    Thread.sleep(100);
                    continue;
                } else {
                    for (String orderId : msgSet) {
                        System.out.println("执行产品订单自动失效，for循环进入======订单编号: " + orderId);
                        LOGGER.info("执行产品订单自动失效，for循环进入======订单编号: " + orderId);
                        AgentOrderInfoDto orderProductDto = agentOrderInfoServiceApi.findByOrderId(Long.parseLong(orderId));
                        if (orderProductDto == null) {
                            continue;
                        }
                        if (orderProductDto.getStatus() != null && orderProductDto.getStatus().equals(BusinessType.OrderType.PAYING.getCode())) {
                            AgentOrderInfoDto dto = new AgentOrderInfoDto();
                            dto.setOrderId(Long.parseLong(orderId));
                            dto.setStatus(BusinessType.OrderType.CLOSED.getCode());//此时表示已关闭的订单
                            dto.setRemark("订单过期自动失效");
                            // 半小时未确认订单，自动按失效处理。
                            if (agentOrderInfoServiceApi.updateAgentOrder(dto)) {
                                LOGGER.info("执行代理商订单自动失效，成功的取消待支付状态======订单编号: " + orderId);
                            } else {
                                LOGGER.info("执行代理商订单自动失效，未成功取消待支付状态======订单编号: " + orderId);
                            }
                        }
                    }
                }
                jedis.zremrangeByScore(BusinessType.QueueKey.ZSET + BusinessType.QueueKey.QUEUE_PRODUCT_ORDER_PAY_TIME, 0, timeStamp);
            } catch (Exception e) {
                LOGGER.error("代理商订单自动完结确认:执行操作======异常: ");
                e.printStackTrace();
            }
        }
    }


    /**
     * 产品套餐支付成功后业务流程
     */
    private void orderProductSuccess() {
        Jedis jedis = kvClient.getJedis();
        String msgSet = null;//订单号、支付方式
        while (true) {
            try {
                DataSourceHolder.clearDataSource();
                msgSet = jedis.lpop(com.lzy.common.constants.OrderDistributePrefix.QUEUE_SETMEAL_PAY);
                if (StringUtil.isBlank(msgSet)) {
                    Thread.sleep(500);
                    continue;
                } else {
                    MsgSetMealDTO msgSetMealDTO = JSON.parseObject(msgSet, MsgSetMealDTO.class);
                    if (null == msgSetMealDTO) {
                        continue;
                    }
                    try {
                        chief(msgSetMealDTO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        //如果执行失败，尝试10次（如果其中某次成功，则跳出循环）
                        for (int i = 0; i < 10; i++) {
                            try {
                                chief(msgSetMealDTO);
                            } catch (Exception e1) {
                                e1.printStackTrace();
                                continue;
                            }
                            break;
                        }
                    }

                }
            } catch (Exception e) {
                LOGGER.error("产品套餐订单支付回调:执行操作======异常:" + e.getMessage());
                e.printStackTrace();
            } finally {
                DataSourceHolder.clearDataSource();
            }
        }
    }

    /**
     * 代理商协议支付成功后业务流程
     */
    private void orderAgentProtocolSuccess() {
        Jedis jedis = kvClient.getJedis();
        String msgSet = null;//订单号、支付方式
        while (true) {
            try {
                DataSourceHolder.clearDataSource();
                msgSet = jedis.lpop(com.lzy.common.constants.OrderDistributePrefix.QUEUE_AGENTPROTOCOL_PAY);
                if (StringUtil.isBlank(msgSet)) {
                    Thread.sleep(500);
                    continue;
                } else {
                    AgentSaleDTO agentSaleDTO = JSON.parseObject(msgSet, AgentSaleDTO.class);
                    if (null == agentSaleDTO) {
                        continue;
                    }
                    try {
                        agentProtocolSuccess(agentSaleDTO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        //如果执行失败，尝试10次（如果其中某次成功，则跳出循环）
                        for (int i = 0; i < 10; i++) {
                            try {
                                agentProtocolSuccess(agentSaleDTO);
                            } catch (Exception e1) {
                                e1.printStackTrace();
                                continue;
                            }
                            break;
                        }
                    }

                }
            } catch (Exception e) {
                LOGGER.error("产品套餐订单支付回调:执行操作======异常:" + e.getMessage());
                e.printStackTrace();
            } finally {
                DataSourceHolder.clearDataSource();
            }
        }
    }

    /**
     * 代理商产品支付成功后业务流程
     */
    private void orderAgentProductSuccess() {
        Jedis jedis = kvClient.getJedis();
        String msgSet = null;//订单号、支付方式
        while (true) {
            try {
                DataSourceHolder.clearDataSource();
                msgSet = jedis.lpop(com.lzy.common.constants.OrderDistributePrefix.QUEUE_AGENTPRODUCT_PAY);
                if (StringUtil.isBlank(msgSet)) {
                    Thread.sleep(500);
                    continue;
                } else {
                    AgentSaleDTO agentSaleDTO = JSON.parseObject(msgSet, AgentSaleDTO.class);
                    if (null == agentSaleDTO) {
                        continue;
                    }
                    try {
                        agentProductSuccess(agentSaleDTO);
                    } catch (Exception e) {
                        e.printStackTrace();
                        //如果执行失败，尝试10次（如果其中某次成功，则跳出循环）
                        for (int i = 0; i < 10; i++) {
                            try {
                                agentProductSuccess(agentSaleDTO);
                            } catch (Exception e1) {
                                e1.printStackTrace();
                                continue;
                            }
                            break;
                        }
                    }

                }
            } catch (Exception e) {
                LOGGER.error("产品套餐订单支付回调:执行操作======异常:" + e.getMessage());
                e.printStackTrace();
            } finally {
                DataSourceHolder.clearDataSource();
            }
        }
    }

    /**
     * 产品套餐支付成功后业务流程
     *
     * @param msgSetMealDTO
     */
    public void chief(MsgSetMealDTO msgSetMealDTO) {
        try {
            LOGGER.error("产品套餐支付成功接口调用，业务执行开始：" + msgSetMealDTO);
            //业务开始
            OrderProductDto orderProduct = orderProductServiceApi.findById(Long.parseLong(msgSetMealDTO.getOrderId()));
            if (orderProduct != null && orderProduct.getStatus().equals(1)) {//待支付
                //1.修改订单信息
                OrderProductDto orderProductDto = new OrderProductDto();
                orderProductDto.setOrderId(Long.parseLong(msgSetMealDTO.getOrderId()));
                orderProductDto.setStatus(BusinessType.OrderType.PAYSUCCESS.getCode());//购买成功状态
                orderProductDto.setPayWay(msgSetMealDTO.getWay());//支付方式
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                orderProductDto.setPayTime(df.format(new Date()));
                if (orderProductServiceApi.update(orderProductDto)) {
                    LOGGER.info("产品套餐支付成功接口调用，修改订单信息成功：orderId=" + msgSetMealDTO.getOrderId());
                } else {
                    LOGGER.info("产品套餐支付成功接口调用，修改订单信息失败：orderId=" + msgSetMealDTO.getOrderId());
                }
                //2.将产品内容送至客户
                OrderProductDto orderDto = orderProductServiceApi.findById(Long.parseLong(msgSetMealDTO.getOrderId()));
                if (orderDto != null) {
                    //订单分利
                    if (orderDto.getType().equals(BusinessType.OrderProductType.PRODUCT.getCode())) {
                        List<OrderProjectRecordDto> list = orderProjectRecordServiceApi.selectOrderProjectRecordByOrderId(orderDto.getOrderId());
                        orderProductServiceApi.calculateProfit(orderDto);
                        if (list != null) {
                            for (OrderProjectRecordDto dto : list) {
                                ProductInfoProjectDto infoProjectDto = productInfoProjectServiceApi.findByProductIdAndProjectId(orderDto.getProductId(), dto.getProjectId());
                                if (infoProjectDto != null) {
                                    dto.setValidTime(infoProjectDto.getValidTime());
                                }
                            }
                        }
                        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                        orderProductFacade.paymentDistribution(list, orderDto);
                    } else if (orderDto.getType().equals(BusinessType.OrderProductType.COUPONS.getCode())) {
                        DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                        ParamBaseDto param = paramServiceApi.queryByKey(CommonConstants.Param.CONTRACT_VERIFY_STATUS);
                        DataSourceHolder.clearDataSource();

                        if (param != null && param.getParamValue().equals(BusinessType.VerifyStatusEnum.VERIFY.getK().toString())) {
                            orderDto.setContractVerify(BusinessType.VerifyStatusEnum.YESVERIFY.getK());
                            orderProductFacade.verifyContract(orderDto);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 卡券宝会员购买卡券支付成功后业务流程
     */
    private void memberBuyCouponSuccess() {
        Jedis jedis = kvClient.getJedis();
        String msgSet = null;//销售商会员id、购买方会员id、购买券参数对象集合
        while (true) {
            try {
                msgSet = jedis.lpop(com.lzy.common.constants.OrderDistributePrefix.QUEUE_COUPON_PAY);
                if (StringUtil.isBlank(msgSet)) {
                    Thread.sleep(100);
                    continue;
                } else {
                    MotorCouponInfoDTO motorCouponInfoDTO = JSON.parseObject(msgSet, MotorCouponInfoDTO.class);
                    if (null == motorCouponInfoDTO) {
                        continue;
                    }
                    LOGGER.error("卡券宝会员购买卡券支付成功接口调用，业务执行开始：" + msgSet);
                    //业务开始
                    Long saleManId = motorCouponInfoDTO.getSaleMan();
                    Long memberId = motorCouponInfoDTO.getMemberId();
                    String orderId = motorCouponInfoDTO.getOrderId();
                    List<MemberBuyCouponParam> list = DozerUtils.maps(motorCouponInfoDTO.getCouponSelectedList(), MemberBuyCouponParam.class);
                    DataSourceHolder.setDataSource(DataSource.DATASOURCE_COMMON);
                    OrderInfoDTO orderInfoDTO = orderApi.selectByOrderId(Long.parseLong(motorCouponInfoDTO.getOrderId()), null);
                    DataSourceHolder.clearDataSource();
                    if (orderInfoDTO != null && orderInfoDTO.getType() != null) {
                        if (orderInfoDTO.getType().toString().equals(com.lzy.order.constants.CommonConstants.Biz.DREAM_PLAN)) {
                            if (memberBuyFacade.memberBuyOfCodeDream(saleManId, memberId, list, orderId)) {
                                LOGGER.error("圆梦计划会员购买卡券支付成功接口调用业务执行成功：" + msgSet);
                            } else {
                                LOGGER.error("圆梦计划会员购买卡券支付成功接口调用业务执行失败：" + msgSet);
                            }
                        } else if (orderInfoDTO.getType().toString().equals(com.lzy.order.constants.CommonConstants.Biz.QUEEN_PLAN)) {
                            if (memberBuyFacade.memberBuyOfQueenPlan(saleManId, memberId, list, orderId)) {
                                LOGGER.error("女王行动会员购买卡券支付成功接口调用业务执行成功：" + msgSet);
                            } else {
                                LOGGER.error("女王行动会员购买卡券支付成功接口调用业务执行失败：" + msgSet);
                            }
                        } else {
                            if (memberBuyFacade.memberBuyOfCode(saleManId, memberId, list, orderId)) {
                                LOGGER.error("卡券宝会员购买卡券支付成功接口调用业务执行成功：" + msgSet);
                            } else {
                                LOGGER.error("卡券宝会员购买卡券支付成功接口调用业务执行失败：" + msgSet);
                            }
                        }
                    } else {
                        LOGGER.error("订单查询失败，会员购买卡券支付成功接口调用业务执行失败：" + msgSet);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("卡券宝会员购买卡券订单支付回调:执行操作======异常:" + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 代理商协议支付成功后业务流程
     */
    public void agentProtocolSuccess(AgentSaleDTO agentSaleDTO) {
        try {
            LOGGER.error("代理商协议支付成功接口调用，业务执行开始：" + agentSaleDTO);
            //业务开始
            AgentOrderInfoDto agentOrderInfoDto = agentOrderInfoServiceApi.findByOrderId(Long.parseLong(agentSaleDTO.getOrderId()));
            if (agentOrderInfoDto != null && agentOrderInfoDto.getStatus().equals(1)) {//待支付
                //1.修改订单信息
                AgentOrderInfoDto agentOrderDto = new AgentOrderInfoDto();
                agentOrderDto.setOrderId(Long.parseLong(agentSaleDTO.getOrderId()));
                agentOrderDto.setStatus(BusinessType.OrderType.PAYSUCCESS.getCode());//购买成功状态
                agentOrderDto.setPayWay(agentSaleDTO.getWay());//支付方式
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                agentOrderDto.setPayTime(df.format(new Date()));
                if (agentOrderInfoServiceApi.updateAgentOrder(agentOrderDto)) {
                    LOGGER.info("代理商协议支付成功接口调用，修改订单信息成功：orderId=" + agentSaleDTO.getOrderId());
                } else {
                    LOGGER.info("代理商协议支付成功接口调用，修改订单信息失败：orderId=" + agentSaleDTO.getOrderId());
                }

                //2.将产品内容送至客户
                AgentOrderInfoDto agentInfoDto = agentOrderInfoServiceApi.findByOrderId(Long.parseLong(agentSaleDTO.getOrderId()));
                if (agentInfoDto != null) {
                    //新增代理商（即改变sys_user_admin表中数据的使用状态）
                    if (agentInfoDto.getMemberId() != null) {
                        if(!agentProfitFacade.updateAgentStatus(agentInfoDto.getMemberId())){
                            LOGGER.info("代理商协议支付成功新增代理商失败：orderId=" + agentSaleDTO.getOrderId());
                        }
                    }
                    //新增协议额外赠送项
                    if(!agentProfitFacade.addProjects(2,agentSaleDTO)){
                        LOGGER.info("代理商协议支付成功新增额外赠送项失败：orderId=" + agentSaleDTO.getOrderId());
                    }
                    //订单分利
                    if (agentInfoDto.getType().equals(BusinessType.OrderProductType.AGENTPROTOCOL.getCode())) {
                        if(!agentProfitFacade.calculateAgentProtocolProfit(agentInfoDto)){
                            LOGGER.info("代理商协议支付成功订单分利失败：orderId=" + agentSaleDTO.getOrderId());
                        }
                    }
                }
                DataSourceHolder.clearDataSource();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 代理商产品支付成功后业务流程
     */
    public void agentProductSuccess(AgentSaleDTO agentSaleDTO) {
        try {
            LOGGER.error("代理商产品支付成功接口调用，业务执行开始：" + agentSaleDTO);
            //业务开始
            AgentOrderInfoDto agentOrderInfoDto = agentOrderInfoServiceApi.findByOrderId(Long.parseLong(agentSaleDTO.getOrderId()));
            if (agentOrderInfoDto != null && agentOrderInfoDto.getStatus().equals(1)) {//待支付
                //1.修改订单信息
                AgentOrderInfoDto agentOrderDto = new AgentOrderInfoDto();
                agentOrderDto.setOrderId(Long.parseLong(agentSaleDTO.getOrderId()));
                agentOrderDto.setStatus(BusinessType.OrderType.PAYSUCCESS.getCode());//购买成功状态
                agentOrderDto.setPayWay(agentSaleDTO.getWay());//支付方式
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                agentOrderDto.setPayTime(df.format(new Date()));
                if (agentOrderInfoServiceApi.updateAgentOrder(agentOrderDto)) {
                    LOGGER.info("代理商产品支付成功接口调用，修改订单信息成功：orderId=" + agentSaleDTO.getOrderId());
                } else {
                    LOGGER.info("代理商产品支付成功接口调用，修改订单信息失败：orderId=" + agentSaleDTO.getOrderId());
                }

                //2.将产品内容送至客户
                AgentOrderInfoDto agentInfoDto = agentOrderInfoServiceApi.findByOrderId(Long.parseLong(agentSaleDTO.getOrderId()));
                if (agentInfoDto != null) {
                    //新增产品包含项
                    if(!agentProfitFacade.addProjects(1,agentSaleDTO)){
                        LOGGER.info("代理商产品支付成功新增包含项失败：orderId=" + agentSaleDTO.getOrderId());
                    }

                    //订单分利
                    if (agentInfoDto.getType().equals(BusinessType.OrderProductType.AGENTPRODUCT.getCode())) {
                        if(!agentProfitFacade.calculateAgentProductProfit(agentInfoDto)){
                            LOGGER.info("代理商产品支付成功订单分利失败：orderId=" + agentSaleDTO.getOrderId());
                        }
                    }
                }
                DataSourceHolder.clearDataSource();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
